package cn.com.xf.web.controller.file;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.com.xf.common.ConfigUtil;
import cn.com.xf.common.Constants;

/**
 * 文件下载统一入口：图片视频采用图片流和视频流，文件采用下载流
 * 
 * @author Administrator
 * 
 */
@Controller
public class DownloadController {
	static String FILE_EXTS = null;
	static String FLV_EXTS = null;
	static String DOC_EXTS = null;
	static {
		FILE_EXTS = "doc,docx,xls,xlsx,ppt,pdf,exe,tif,xml,iso,htm,html,txt,zip,rar,gz,bz2,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,swf,flv,f4v,gif,jpg,jpeg,png,bmp";
		FLV_EXTS = "flv,f4v,mp4";
		DOC_EXTS = "doc,docx";
	}

	/**
	 * 图片流输出
	 * 
	 * @param imageName
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/imagextra/{imageName:.*}", method = RequestMethod.GET)
	public void imagextra(@PathVariable String imageName, HttpServletRequest request, HttpServletResponse response) {
		FileInputStream fis = null;
		response.setContentType("image/jpeg");
		try {
			OutputStream out = response.getOutputStream();
			File file = new File(ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
					+ Constants.ABSOLUTE_ROOT_IMAGE_PATH + File.separator + imageName);
			if (file.exists()) {
				fis = new FileInputStream(file);
				byte[] b = new byte[fis.available()];
				fis.read(b);
				out.write(b);
				out.flush();
			} else {
				BufferedImage bi = generateDefaultImage(2);
				ImageIO.write(bi, "jpg", out);
				out.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 文件流输出，下载文件
	 * 
	 * @param fileName
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/filextra/{fileName:.*}", method = RequestMethod.GET)
	public void fileDownload(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		OutputStream out = null;
		// 1.验证文件扩展名
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		if (!Arrays.<String> asList(FILE_EXTS.split(",")).contains(fileExt)) {
			// 非法扩展名
			out = response.getOutputStream();
			response.setContentType("image/jpeg");
			BufferedImage bi = generateDefaultImage(1);
			ImageIO.write(bi, "jpg", out);
			out.flush();
			return;
		}
		// 2.在文件系统查找文件
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		try {
			File file = new File(ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
					+ Constants.ABSOLUTE_ROOT_FILE_PATH + File.separator + fileName);
			if (file.exists()) {
				long fileLength = file.length();
				response.setContentType("application/x-msdownload;");
				response.setHeader("Content-disposition",
						"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
				response.setHeader("Content-Length", String.valueOf(fileLength));
				bis = new BufferedInputStream(new FileInputStream(file));
				bos = new BufferedOutputStream(response.getOutputStream());
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
				bos.flush();
			} else {
				out = response.getOutputStream();
				response.setContentType("image/jpeg");
				BufferedImage bi = generateDefaultImage(0);
				ImageIO.write(bi, "jpg", out);
				out.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
			if (out != null)
				out.close();
		}
	}

	/**
	 * 视频流输出
	 * 
	 * @param fileName
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/flvextra/{fileName:.*}", method = RequestMethod.GET)
	public void flvOutStream(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		OutputStream out = null;
		// 1.验证文件扩展名
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		if (!Arrays.<String> asList(FLV_EXTS.split(",")).contains(fileExt)) {
			// 非法扩展名
			out = response.getOutputStream();
			response.setContentType("image/jpeg");
			BufferedImage bi = generateDefaultImage(1);
			ImageIO.write(bi, "jpg", out);
			out.flush();
			return;
		}

		// 查找文件
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		try {

			File file = new File(ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
					+ Constants.ABSOLUTE_ROOT_FLV_PATH + File.separator + fileName);

			if (file.exists()) {
				long fileLength = file.length();
				response.setContentType("video/x-flv;");
				response.setHeader("Content-disposition",
						"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
				response.setHeader("Content-Length", String.valueOf(fileLength));
				bis = new BufferedInputStream(new FileInputStream(file));
				bos = new BufferedOutputStream(response.getOutputStream());
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
				bos.flush();
			} else {
				out = response.getOutputStream();
				response.setContentType("image/jpeg");
				BufferedImage bi = generateDefaultImage(0);
				ImageIO.write(bi, "jpg", out);
				out.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
			if (out != null)
				out.close();
		}
	}

	/**
	 * 文件流输出，下载文件:下载简历
	 * 
	 * @param fileName
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/resumextra/{fileName:.*}", method = RequestMethod.GET)
	public void resumeDownload(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		OutputStream out = null;
		// 1.验证文件扩展名
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		if (!Arrays.<String> asList(DOC_EXTS.split(",")).contains(fileExt)) {
			// 非法扩展名
			out = response.getOutputStream();
			response.setContentType("image/jpeg");
			BufferedImage bi = generateDefaultImage(1);
			ImageIO.write(bi, "jpg", out);
			out.flush();
			return;
		}
		// 2.在文件系统查找文件
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;
		try {
			File file = new File(ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
					+ Constants.ABSOLUTE_ROOT_RESUME_PATH + File.separator + fileName);
			if (file.exists()) {
				long fileLength = file.length();
				response.setContentType("application/msword;");
				response.setHeader("Content-disposition",
						"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
				response.setHeader("Content-Length", String.valueOf(fileLength));
				bis = new BufferedInputStream(new FileInputStream(file));
				bos = new BufferedOutputStream(response.getOutputStream());
				byte[] buff = new byte[2048];
				int bytesRead;
				while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
					bos.write(buff, 0, bytesRead);
				}
				bos.flush();
			} else {
				out = response.getOutputStream();
				response.setContentType("image/jpeg");
				BufferedImage bi = generateDefaultImage(0);
				ImageIO.write(bi, "jpg", out);
				out.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
			if (out != null)
				out.close();
		}
	}

	/**
	 * 生成一张默认的小图片替代无文件
	 * 
	 * @return
	 */
	private BufferedImage generateDefaultImage(int type) {
		BufferedImage bi = new BufferedImage(70, 60, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = (Graphics2D) bi.getGraphics();
		g2.setBackground(Color.WHITE);
		g2.clearRect(0, 0, 70, 60);
		g2.setPaint(Color.BLACK);
		String tip = "";
		if (type == 0) {
			tip = "文件不存在";
		} else if (type == 1) {
			tip = "扩展名错误";
		} else if (type == 2) {
			tip = "信丰物流";
		}
		g2.drawString(tip, 5, 35);
		return bi;
	}
}